/*
 * LeafNode.cpp
 *
 *  Created on: Oct 9, 2011
 *      Author: USHonDan
 */

#include "LeafNode.h"

LeafNode::LeafNode() : Node(LEAF_NODE) {
	_recPtrs = new Record*[GetD()+1];
	_nextLeaf = NULL;
	_previousLeaf = NULL;
}

LeafNode::~LeafNode() {
	delete _recPtrs;
}

//Insert key and record into leaf node, pushing higher keys further along array
int LeafNode::InsertRecord(int key, Record *rec) {
	int insertIdx = InsertKey(key);
	if(insertIdx != -1) {
		for(int idx = insertIdx; idx < NumberOfKeys(); idx++) { //don't need <= in this case because InsertKey has already incremented the index count
			swap(_recPtrs[idx], rec);
		}
	}

	return insertIdx;
}

//Retrieve record for input key
//Returns NULL if key not found
Record *LeafNode::GetRecord(int key) {
	int idx = SearchKey(key); //returns index of nearest index
	if(idx < GetD() && _keys[idx] == key) //so need to check for equality here
		return _recPtrs[idx];
	else
		return NULL;
}

//Pointer to next leaf
LeafNode *LeafNode::GetNext() {
	return _nextLeaf;
}

//Pointer to previous leaf
LeafNode *LeafNode::GetPrevious() {
	return _previousLeaf;
}

//Set previous leaf pointer
void LeafNode::SetPrevious(LeafNode *leaf) {
	_previousLeaf = leaf;
}

//Set next leaf pointer
void LeafNode::SetNext(LeafNode *leaf) {
	_nextLeaf = leaf;
}

//Split leaf node into next empty leaf node in nodegroup around input key index
int LeafNode::SplitLeaf(LeafNode *nextEmpty, int splitIdx) {
	SetNext(nextEmpty);
	nextEmpty->SetPrevious(this);

	for(int idx = splitIdx; idx < NumberOfKeys(); idx++)
		nextEmpty->InsertRecord(_keys[idx], _recPtrs[idx]);

	SetNumberOfKeys(splitIdx); //split node will now ignore past entries

	return _keys[splitIdx-1]; //return last index in first of split nodes
}
